package com.site.common.util;

import java.io.File;
import java.io.IOException;

import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.model.JavaSource;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import com.thoughtworks.qdox.model.Type;

public class ParsedJavaSource {

  private final JavaSource src;
  private String reportScript;
  private String metaDataScript;
  private String imports;

  public ParsedJavaSource(String fileName) throws IOException {
    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSource(new File(fileName));
    src = builder.getSources()[0];
    tokenizeImports();
    metaDataScript = appendImportsToMethodBody("metadataScript");
    reportScript = appendImportsToMethodBody("reportScript",
        new Type[] { new Type("com.urbancode.anthill3.domain.reporting.ReportMetaData") });
  }

  private void tokenizeImports() {
    StringBuilder builder = new StringBuilder("// Generated by AhpTools: Do not edit in the browser.\n");
    String[] imported = src.getImports();
    for (String line:imported){
      builder.append("import ").append(line).append(";\n");
    }
    imports = builder.toString();
  }

  private String appendImportsToMethodBody(String methodName) {
    return appendImportsToMethodBody(methodName, null);
  }

  private String appendImportsToMethodBody(String methodName, Type[] params) {
    JavaClass clazz = src.getClasses()[0];
    JavaMethod metaDataMethod = clazz.getMethodBySignature(methodName, params);

    StringBuilder builder = new StringBuilder();
    builder.append(imports);
    builder.append(metaDataMethod.getSourceCode());
    return builder.toString();
  }

  public String metaDataScript() {
    return metaDataScript;
  }

  public String reportScript() {
    return reportScript;
  }
}
